package com.example.sxmall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.sxmall.common.dto.MailDto;
import com.example.sxmall.dao.pojo.Admins;
import com.example.sxmall.dao.mapper.AdminsMapper;
import com.example.sxmall.dao.pojo.Percontent;
import com.example.sxmall.dao.pojo.Permission;
import com.example.sxmall.dao.pojo.Users;
import com.example.sxmall.service.AdminsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.sxmall.service.PercontentService;
import com.example.sxmall.service.PermissionService;
import com.example.sxmall.service.UsersService;
import com.example.sxmall.until.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhang
 * @since 2022-03-22
 */
@Service
public class AdminsServiceImpl extends ServiceImpl<AdminsMapper, Admins> implements AdminsService {
    @Autowired
    UsersService usersService;

    //Spring Boot 提供了一个发送邮件的简单抽象，使用的是下面这个接口，这里直接注入即可使用
    @Autowired(required=false)
    private JavaMailSender javaMailSender;


    @Autowired
    PermissionService permissionService;
    @Autowired
    PercontentService percontentService;
    @Autowired
    AdminsMapper adminsMapper;

    @Autowired
    RedisUtil redisUtil;
    private Object String;

    @Override
    public Admins getByAdminsName(String username) {
        return getOne(new QueryWrapper<Admins>().eq("acount", username));
    }

    /*获取权限信息*/

    @Override
    public String getAdminsAuthorityInfo(Integer adminsId) {
        Admins admins = adminsMapper.selectById(adminsId);

        String authority = "";

        if (redisUtil.hasKey("GrantedAuthority:" + admins.getAcount())){
            authority = (String) redisUtil.get("GrantedAuthority:" + admins.getAcount());
        }else {
            //获取权限名称
            List<Permission> permissions = permissionService.list(new QueryWrapper<Permission>().
                    inSql("perid", "select perid from admins_permis where aid = " + adminsId));

            if (permissions.size() > 0) {
                //获取所有权限名
                String perCode = permissions.stream().map(r -> "ROLE_"+r.getPercode()).collect(Collectors.joining(","));
                authority = perCode.concat(",");
            }

            //获取具体权限
             List<Integer> pcid = adminsMapper.getNavPercontentsId(adminsId);
            if (pcid.size() > 0){
                List<Percontent> percontents = percontentService.listByIds(pcid);

                String pcitems = percontents.stream().map(per -> per.getPcitems()).collect(Collectors.joining(","));

                authority = authority.concat(pcitems);
            }


            //添加缓存
            redisUtil.set("GrantedAuthority:" + admins.getAcount(), authority, 60 * 60);
        }
        return authority;
    }

    //删除缓存
    @Override
    public void clearAdminAuthorityInfo(String username) {
        redisUtil.del("GrantedAuthority:"+username);
    }

    @Override
    public void clearAdminAuthorityInfoByPermisId(Integer permissionId) {
        List<Admins> admins = this.list(new QueryWrapper<Admins>().inSql("aid", "SELECT aid FROM admins_permis WHERE perid = " + permissionId));
        admins.forEach(a ->{
            this.clearAdminAuthorityInfo(a.getAcount());
        });
    }

    @Override
    public void clearAdminAuthorityInfoByPerconId(Integer pctId) {
        List<Admins> admins = adminsMapper.listByPerconId(pctId);

        admins.forEach(a ->{
            this.clearAdminAuthorityInfo(a.getAcount());
        });
    }

    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String from;
    /*发送邮件*/
    @Override
    public Result sendMail(MailDto mailDto) {
        //创建SimpleMailMessage对象
        SimpleMailMessage mailMessage = new SimpleMailMessage();

        List<String> eamilList = new ArrayList<>();

        if (mailDto.getUserId()==null){
            return Result.fail("请选选择收件人");
        }
        List<Integer> userId = mailDto.getUserId();

        for (Integer id:userId) {
            Users users = usersService.getById(id);
            eamilList.add(users.getUemail());
        }

        String[] strings = eamilList.toArray(new String[eamilList.size()]);

        mailMessage.setFrom(from);
        mailMessage.setTo(strings);
        mailMessage.setSubject(mailDto.getSubject());
        mailMessage.setText(mailDto.getContent());
        try {
            javaMailSender.send(mailMessage);
            //log.info("邮件接收人" + mailDto.getTo() + "主题" + mailDto.getSubject() + "内容" + mailDto.getContent() + "邮件发送成功");
        } catch (Exception e) {
            log.error("邮件接收人"  + "主题" + mailDto.getSubject() + "内容" + mailDto.getContent() + "邮件发送出现异常");
            log.error("异常信息为" + e.getMessage());
            log.error("异常堆栈信息为-->");
            e.printStackTrace();

        }
        return Result.succ("发送成功");
    }
}
